#!/usr/bin/env coffee

import { dirname,join } from 'path'
import imap from './imap'
import fs from 'fs'
import __dirname from './__dirname'
import puppeteer from 'puppeteer'
import sleep from 'await-sleep'

###

login_feishu = (browser, page)=>

  #await page._client.send('Page.setDownloadBehavior', {
  #  behavior: 'allow'
  #  downloadPath: DIR_DOWNLOAD
  #})

  loop
    url = 'https://xvccapical.feishu.cn/admin/drive/cloud-space'

    await page.goto(url, {
      waitUntil: 'networkidle2'
    })
    title = await page.title()
    console.log title
    if await page.$ 'div[data-clipboard-text="https://www.feishu.cn/admin"]'
      console.log "logined"
      break
    else
      await login(page)
      await sleep 6000

  page = await browser.newPage()

  await Promise.all [
    new Promise (resolve)=>
      page.on 'response', (res)=>
        url = res.url()
        if url.indexOf('/suite/admin/space_manage/search') + 1

          browser = await page.browser()
          p = await browser.newPage()
          await p.goto(
            "https://xvccapical.feishu.cn/drive/home/"
            {
              waitUntil: 'networkidle2'
            }
          )

          await p.close()

          headers = {}
          cookie = []
          for i in await page.cookies()
            if i.name == 'csrf_token'
              headers["x-csrf-token"] = i.value
            else if i.name == '_csrf_token'
              headers["x-csrftoken"] = i.value
            else
              cookie.push i.name+"="+i.value

          headers.cookie = cookie.join '; '

          fs.writeFileSync HEADERS_JSON, JSON.stringify(headers)
          resolve()

    page.goto(url, {
      waitUntil: 'networkidle2'
    })
  ]

click = (page, cls)=>
  await page.waitForSelector cls
  await page.click cls

login = (page)=>
  await click page, '.sso-button-account'

  await click page, '.login-with-account-container .base-tabs-bar:nth-child(2)'

  if not await page.$ '.base-check-box.checked'
    await page.click '.base-check-box'

  input = await page.waitForSelector('.base-input')
  await input.type CONFIG.mail
  await input.focus()

  await page.keyboard.press('Enter')

  await sleep 3000

  password_input = '.base-input[type=password]'
  password_input = await page.waitForSelector password_input

  console.log password_input

  await password_input.type CONFIG.password
  await password_input.focus()

  await page.keyboard.press('Enter')

  console.log "请稍等 ···"
  await sleep(6000)

  if await page.$ '.pp-base-code-box'

    code = await imap()
    console.log '验证码',code
    if code
      for i in code
        console.log i
        await page.keyboard.press(i)
        await sleep(500)


hide_puppeteer = (page)=>

  # Puppeteer在工作中是如何伪装自己的(爬虫与反爬虫) https://juejin.cn/post/6872666746139246606
  await page.evaluateOnNewDocument(
    =>
      newProto = navigator.__proto__
      delete newProto.webdriver
      navigator.__proto__ = newProto
  )
  await page.evaluateOnNewDocument =>
    window.navigator.chrome = {
      runtime: {}
    }
###

export default =>
  browser = await puppeteer.launch({
    headless: true
    #headless: false
    ignoreHTTPSErrors: true
    args: ['--no-sandbox','--lang=zh-CN']
    userDataDir: join(__dirname,"cache")
  })

  page = await browser.newPage()

  url = 'http://redash.hirect.ai/'
  await page.goto(url, {
    waitUntil: 'networkidle2'
  })
  await page.setExtraHTTPHeaders({
    'Accept-Language': 'zh-CN,zh;q=0.9,zh-TW;q=0.8,zh-HK;q=0.7,en;q=0.6'
  })


  #await page.emulate(puppeteer.devices['iPhone X'])

  #await hide_puppeteer(page)

  await sleep(30000)
  await browser.close()


